//
//  DailyDetailViewController.m
//  花花时尚
//
//  Created by 霍文轩 on 15/8/26.
//  Copyright (c) 2015年 霍文轩. All rights reserved.
//

#import "DailyDetailViewController.h"
#import "Define.h"
#import "AsyncGETConnection.h"
#import "DetailShowImageView.h"
#import "DetailImageDownViewController.h"
#import "ArticleModel.h"
#import "GiFHUD.h"

#import "UIImageView+WebCache.h"

#import "CollectProgramaDatabase.h"
#import "CollectProgramaModel.h"

#import "NightMode.h"


@interface DailyDetailViewController () <UIScrollViewDelegate,DetailShowImageViewDelegate>{
    int beforeYOffset;   // 记录scrollView之前滚动的位置
    float heightForViews;  // 所有视图的高度
}
@property (nonatomic,retain) UIView * downView;
@property (nonatomic,retain) UIScrollView * scrollView;
@property (nonatomic,retain) NSDictionary * allInfoDic; // 所有信息的字典
@property (nonatomic,retain) NSArray * imgsArray; // 图片列表
@property (nonatomic,retain) DetailShowImageView * coverImg; // 标题图片
@property (nonatomic,assign) CGRect coverImageRect; // 标题图片的尺寸
@property (nonatomic,assign) CGFloat scale;
@property (nonatomic,retain) ArticleModel * model;
@end

@implementation DailyDetailViewController
-(void)dealloc{
    [_model release];
    [_scrollView release];
    [_downView release];
    [_allInfoDic release];
    [_imgsArray release];
    [_coverImg release];
    [super dealloc];
}
-(instancetype)initWithModel:(ArticleModel *)model{
    self = [super init];
    if(self){
        beforeYOffset = 0.0;
        heightForViews = 0.0;
        self.model = model;
        
        [GiFHUD setGifWithImageName:@"33333333333.gif"];
        
        [GiFHUD show];
//        MBProgressHUD * mb = [[MBProgressHUD alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
//        [self.view addSubview:mb];
//        mb.userInteractionEnabled = NO;
//        mb.labelText = @"加载中...";
//        [mb show:YES];
        
        // 得到的lists是一个数组，只有一个元素，保存所有的图片信息以及图集的名字和描述
        // lists的imgs是一个数组，里面的每个字典储存图片的信息，和每个图片的描述
        NSString * urlString = [NSString stringWithFormat:@"http://mrosevision.sinaapp.com/mfashion_api_v200.php?ac=getarticleinfo&did=640%%2C1136%%2CiPhone5%%2C2&id=%lld&format=json&dim=02%%3A00%%3A00%%3A00%%3A00%%3A00&dic=AppStore&div=2.1.0&djb=1&diu=0F607264FC6318A92B9E13C65DB7CD3C",model.id];
        [AsyncGETConnection asyncConnectionWithURLString:urlString parmaters:nil block:^(NSData *data) {
            NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray * array = [dic objectForKey:@"lists"];
            
//            [mb removeFromSuperview];
//            [mb release];
            [GiFHUD dismiss];
            self.allInfoDic = [array objectAtIndex:0];  // 大字典
            self.imgsArray = [_allInfoDic objectForKey:@"imgs"];  // 图片的数组

            if(_imgsArray.count == 1){   // 根据图片数量创建不同的界面
                [self createAImage];
            }else{
                [self createScrollAndImages];
            }
        }];
    }
    return  self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    UIImage * backImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NightMode nightModeON]?@"back":@"back_light" ofType:@"png"]];
    self.view.backgroundColor = [UIColor colorWithPatternImage:backImage];

    [self createDownView];
}
// 创建下面的视图栏
-(void)createDownView{
    self.downView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-49, self.view.frame.size.width, 49)];
    UIImage * detailDownImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NightMode nightModeON]?@"detaildown":@"detaildown_light" ofType:@"png"]];
    _downView.backgroundColor = [UIColor colorWithPatternImage:detailDownImage];
    [self.view addSubview:_downView];
    [_downView release];
    
    UIButton * returnButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 10, 30, 30)];
    UIImage * returnButtonImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dailyreturn" ofType:@"png"]];
    returnButton.backgroundColor = [UIColor colorWithPatternImage:returnButtonImage];
    [returnButton addTarget:self action:@selector(returnButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [_downView addSubview:returnButton];
    [returnButton release];
    
    UIButton * collectButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    collectButton.center = CGPointMake(self.view.frame.size.width/2, _downView.frame.size.height/2);
    if([CollectProgramaDatabase selectWithId:_model.id] == nil){
        collectButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"collect_white"]];
    }else{
        collectButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"collect_red"]];
    }
    [_downView addSubview:collectButton];
    [collectButton addTarget:self action:@selector(collect:) forControlEvents:UIControlEventTouchUpInside];
    [collectButton release];
}

#pragma mark - 收藏
-(void)collect:(UIButton *)button{
    if([CollectProgramaDatabase selectWithId:_model.id] == nil){
        NSDictionary * simgsDic = [_model.simgs objectAtIndex:0];
        NSInteger width = [[simgsDic objectForKey:@"width"] integerValue];
        NSInteger height = [[simgsDic objectForKey:@"height"] integerValue];
        CollectProgramaModel * collectModel = [CollectProgramaModel collectModelWithId:_model.id title:_model.title url:[simgsDic objectForKey:@"url"] height:height width:width];
        [CollectProgramaDatabase insertWithModel:collectModel];
        button.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"collect_red"]];
    }else{
        [CollectProgramaDatabase deleteWithId:_model.id];
        button.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"collect_white"]];
    }
}

#pragma mark - 创建多个图片的scrollview
-(void)createScrollAndImages{
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 49)];
    _scrollView.delegate = self;
    _scrollView.alwaysBounceVertical = YES; // 即使到了边界也能继续纵向滚动
    [self.view addSubview:_scrollView];
    [_scrollView release];
    
    // 计算coverImage的宽高比例  显示出来
    NSDictionary * imgDic = [_imgsArray objectAtIndex:0];
    NSNumber * width = [imgDic objectForKey:@"width"];
    NSNumber * height = [imgDic objectForKey:@"height"];
    CGFloat scale = [width floatValue]/[height floatValue];
    
    self.coverImageRect = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width / scale); // 记录实际的尺寸
    
    self.coverImg = [[DetailShowImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width / scale) text:@""];
    _coverImg.delegate = self;
    heightForViews += _coverImg.frame.size.height;  // 累加到总高度上
    _scrollView.contentSize = CGSizeMake(0, heightForViews);  //  同时增加contentSize
    [_coverImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kWebImageDomain,[imgDic objectForKey:@"url"]]]];
    [_scrollView addSubview:_coverImg];
    [_coverImg release];
    
    // 标题label
    UILabel * titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, heightForViews, self.view.frame.size.width - 20, 90)];
    heightForViews += titleLabel.frame.size.height;
    _scrollView.contentSize = CGSizeMake(0, heightForViews);
    titleLabel.font = [UIFont boldSystemFontOfSize:25];
    titleLabel.textAlignment = NSTextAlignmentLeft;
    titleLabel.textColor = [NightMode nightModeON]?[UIColor whiteColor]:[UIColor blackColor];
    titleLabel.numberOfLines = 2;
    titleLabel.text = [_allInfoDic objectForKey:@"title"];
    [_scrollView addSubview:titleLabel];
    [titleLabel release];
    
    // 描述label
    UILabel * contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, heightForViews, self.view.frame.size.width - 20, [self heightWithText:[_allInfoDic objectForKey:@"content"]])];
    heightForViews += contentLabel.frame.size.height;
    _scrollView.contentSize = CGSizeMake(0, heightForViews);
    contentLabel.text = [_allInfoDic objectForKey:@"content"];
    [_scrollView addSubview:contentLabel];
    contentLabel.font = [UIFont systemFontOfSize:19];
    contentLabel.numberOfLines = 0;
    contentLabel.textColor = [NightMode nightModeON]?[UIColor whiteColor]:[UIColor blackColor];
    [contentLabel release];
    
    [self createImages];
    
    [self.view addSubview:_downView]; // 让downView保持在上方
}
// 创建一些图片
-(void)createImages{
    for (NSDictionary* imgDic in _imgsArray) {
        if(imgDic != [_imgsArray objectAtIndex:0]){  // 如果不是第一个元素，就创建ImageView
            // 计算coverImage的宽高比例  显示出来
            NSNumber * width = [imgDic objectForKey:@"width"];
            NSNumber * height = [imgDic objectForKey:@"height"];
            self.scale = [width floatValue]/[height floatValue];
            
            DetailShowImageView * imageView = [[DetailShowImageView alloc] initWithFrame:CGRectMake(0, heightForViews + 10, self.view.frame.size.width, self.view.frame.size.width / _scale) text:[imgDic objectForKey:@"comment"]];
            imageView.delegate = self;
            heightForViews += ( imageView.frame.size.height + 10 );  // 累加到总高度上
            _scrollView.contentSize = CGSizeMake(0, heightForViews);  //  同时增加contentSize
            [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kWebImageDomain,[imgDic objectForKey:@"url"]]]];
            [_scrollView addSubview:imageView];
            [imageView release];
        }
    }
}
#pragma  mark -  创建一个图片
-(void)createAImage{
    // 计算coverImage的宽高比例  显示出来
    NSDictionary * imgDic = [_imgsArray objectAtIndex:0];
    NSNumber * width = [imgDic objectForKey:@"width"];
    NSNumber * height = [imgDic objectForKey:@"height"];
    CGFloat scale = [width floatValue]/[height floatValue];
    
    // 标题label
    UILabel * titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, heightForViews, self.view.frame.size.width - 20, 90)];
    heightForViews += titleLabel.frame.size.height;

    titleLabel.font = [UIFont boldSystemFontOfSize:25];
    titleLabel.textAlignment = NSTextAlignmentLeft;
    titleLabel.textColor = [NightMode nightModeON]?[UIColor whiteColor]:[UIColor blackColor];
    titleLabel.numberOfLines = 2;
    titleLabel.text = [_allInfoDic objectForKey:@"title"];
    [self.view addSubview:titleLabel];
    [titleLabel release];
    
    // 描述label
    UILabel * contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, heightForViews, self.view.frame.size.width - 20, [self heightWithText:[_allInfoDic objectForKey:@"content"]])];
    heightForViews += contentLabel.frame.size.height;
    contentLabel.text = [_allInfoDic objectForKey:@"content"];
    [self.view addSubview:contentLabel];
    contentLabel.font = [UIFont systemFontOfSize:19];
    contentLabel.numberOfLines = 0;
    contentLabel.textColor = [NightMode nightModeON]?[UIColor whiteColor]:[UIColor blackColor];
    [contentLabel release];
    
    DetailShowImageView * specialImg = [[DetailShowImageView alloc] initWithFrame:CGRectMake(0, heightForViews + 40, self.view.frame.size.width, self.view.frame.size.width / scale) text:@""];
    specialImg.delegate = self;
    // 如果图片的高度大于剩余的高度，那么把图片放在下面，否则放到中间
    if(self.view.frame.size.width/scale < self.view.frame.size.height - heightForViews){
        specialImg.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2);
    }else{
        specialImg.frame = CGRectMake(0, heightForViews + 50, self.view.frame.size.width, self.view.frame.size.width/scale);
    }
    [specialImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kWebImageDomain,[imgDic objectForKey:@"url"]]]];
    [self.view addSubview:specialImg];
    
    [specialImg release];
    
    [self.view addSubview:_downView];
}

#pragma mark - scrollView代理方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

    float currentYOffset = scrollView.contentOffset.y;
        // 向上拉
        if(currentYOffset > beforeYOffset){ // 判断上拉还是下降
            // 如果图片没有回到原来位置就还原大小，如果在原来位置就上升
            if(scrollView.contentOffset.y>0)
                _coverImg.frame = CGRectMake(0, 0, _coverImg.frame.size.width, _coverImg.frame.size.height);
            else{
                _coverImg.frame = CGRectMake(0, 0, _coverImageRect.size.width-scrollView.contentOffset.y, _coverImageRect.size.height-scrollView.contentOffset.y/_scale); // 除以比例，按照比例拉伸
                _coverImg.center = CGPointMake(self.view.frame.size.width/2,( _coverImageRect.size.height + scrollView.contentOffset.y)/2);
            }
        }
        else{  // 向下拉时图片随着变大
            if(scrollView.contentOffset.y<0)
            {
                _coverImg.frame = CGRectMake(0, 0, _coverImageRect.size.width-scrollView.contentOffset.y, _coverImageRect.size.height-scrollView.contentOffset.y/_scale);  // 除以比例，按照比例拉伸
                _coverImg.center = CGPointMake(self.view.frame.size.width/2,( _coverImageRect.size.height + scrollView.contentOffset.y)/2);
            }else{
                _coverImg.frame = CGRectMake(0, 0, _coverImg.frame.size.width, _coverImg.frame.size.height);
            }
        }
    beforeYOffset = currentYOffset;
}
-(void)returnButtonClick{
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}
#pragma mark -  根据文本设定大小
- (CGFloat)heightWithText:(NSString *)text{
    CGRect rect = [text boundingRectWithSize:CGSizeMake(self.view.frame.size.width, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20]} context:nil]; // 第一个参数：预定的矩形大小。第二个：图形选项。第三个：属性字典，设置字体和字体大小，一般和cell中设置的一样。第四个：内容文本，一般为空
    return rect.size.height;
}
#pragma mark -  点击图片进入图片下载页
-(void)enterImageWithImage:(UIImage *)mainImage imgRect:(CGRect)imgRect{
    NSDictionary * imgDic = [_imgsArray objectAtIndex:0];
    NSString * linkURL = [imgDic objectForKey:@"link_url"]; // 图片字典中的链接，是图片或者mp4
    
    NSString * typeString = [linkURL substringFromIndex:linkURL.length - 3]; // 得到最后三个字符，如果是mp4，那么就是视频，否则是图片
    // 如果是图片就创建图片的详情，如果是mp4，就创建mp4播放器
    if([typeString isEqualToString:@"mp4"]){
    }else{
        DetailImageDownViewController * specialVC = [[DetailImageDownViewController alloc] initWithImage:mainImage imgRect:imgRect linkURL:linkURL];
        specialVC.modalTransitionStyle = 2; // 切换界面动画效果
        [self presentViewController:specialVC animated:YES completion:^{   }];
    }
}
@end
